<template>
  <n-card :bordered="false" class="proCard">
    <!-- 学期模态框 -->
    <n-space>
      <n-select v-model:value="selectOptionValue" :options="selectOption" style="width: 200px;"/>
      <n-button type="success" secondary strong @click="setWorkingSemester">设置为工作学期</n-button>
      <n-button type="warning" secondary strong @click="createNewSemester">创建新学期</n-button>
    </n-space>

    <!-- 新建学期模态框 -->
    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建学期">
      <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80" class="py-4">
        <n-form-item label="学期" path="">
          <n-date-picker v-model:value="selectYear" type="year" quarter-format="q" clearable />
          <n-select v-model:value="selectSemester" :options="selectSemesterOption" style="width: 200px;" />
        </n-form-item>

        <n-form-item label="开始时间" path="">
          <n-date-picker v-model:formatted-value="createNewTermTime" value-format="yyyy-MM-dd" type="date" />
        </n-form-item>

      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmCreateSemester">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 排课列表 -->
    <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row: ListDataAboutArrangeClass) => row.id"
      ref="actionRef" :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :scroll-x="1090">
    </BasicTable>

  </n-card>

  <!-- 排课模态框 -->
  <n-modal v-model:show="showArrangeClassModal" :show-icon="false" preset="dialog" title="排课" style="width: 300px;">

    <n-form :model="ArrangeClassformParams" :rules="rules" ref="arrangeClassformParamsformRef" label-placement="left"
      :label-width="80" class="py-4">
      <n-form-item label="查看可排课教室" path="">
        <n-select v-model:value="ArrangeClassSelectOptionValue" :options="ArrangeClassSelectOption" />
      </n-form-item>
    </n-form>

    <template #action>
      <n-space>
        <n-button @click="() => (showArrangeClassModal = false)">取消</n-button>
        <n-button type="info" :loading="formBtnLoading" @click="submitArrangeClass">确定</n-button>
      </n-space>
    </template>
  </n-modal>

</template>

<script lang="ts" setup>
import { h, reactive, ref, onMounted } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';

 
import { getAllTerm } from '@/api/table/list';
import { setWorkingSemesterApi, creatNewSemesterApi } from '@/api/admin/arrangeClass'
import { getArrangeClassListApi, getFreeLabListApi, updateArrangeClassApi, updataArrangeInfoClassApi } from '@/api/admin/arrangeClass'
import { columnsAboutArrangeClass, ListDataAboutArrangeClass } from './columns';

import { useRouter } from 'vue-router';
import { type FormRules, NButton } from 'naive-ui';

async function getTerm() {

  const terms = await getAllTerm()

  let list = new Array();

  for (let term of terms) {
    list.push({
      label: term.term + '',
      value: term.id,
    },)
  }
  selectOption.value = list
  return list

}

onMounted(() => {
  getTerm()
})

const columns = ref(columnsAboutArrangeClass);

const selectOptionValue = ref(null)
const selectYear = ref(null)
const selectSemester = ref(null)
const createNewTermTime = ref(null)

const selectSemesterOption = ref([
  {
    label: "1",
    value: 1,
  },
  {
    label: '2',
    value: 2,
  },
])
const selectOption = ref([
  {
    label: "2022-2023-1",
    value: 0,
  },
  {
    label: '2022-2023-2',
    value: 1,
  },
  {

    label: '2023-2024-1',
    value: 2
  },
])

const rules: FormRules = {
  default: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入',
  },

};

const router = useRouter();
const formRef: any = ref(null);
const actionRef = ref();

const showModal = ref(false);
const showArrangeClassModal = ref(false);
const formBtnLoading = ref(false);
const formParams = reactive({
  name: '',
  address: '',

  id: '',
  username: '',
  account: '',
  role: '',
  pro_rank: '',
  major: '',
  class_name: '',

  semester: ''

});
const ArrangeClassformParams = reactive({
  selectClass: ''
});
const ArrangeClassSelectOptionValue = ref(null)
const ArrangeClassSelectOption = ref()


const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record: any) {
    return h(TableAction as any, {
      style: 'NButton',
      actions: [
        {
          label: '排课',
          onClick: arrangeClass.bind(null, record),
          type: 'warning',
          ifShow: () => {
            return isManage(record);
          },
        },
      ],
    });
  },
});
function isManage(record: any) {
  return record.state == 0
}

let labList
let applicationId

async function arrangeClass(record: any) {

  applicationId = record.id

  labList = await getFreeLabListApi({
    applicationId: record.id
  })

  //生成可选课列表
  let list = new Array();
  if (labList == null) {
    //排课冲突
  } else {
    //可以进行排课
    for (let lab of labList) {
      list.push({
        label: lab.labName,
        value: lab.labId
      })
    }
  }


  if (list.length == 0) {
    //排课冲突  
    window['$message'].error("排课冲突 无可用教室!");
    //设置当亲排课状态为已排课--排课失败
    updateArrangeClassApi({
      id: record.id,
      state: 1
    })

    reloadTable()
  } else {
    ArrangeClassSelectOption.value = list as any
    showArrangeClassModal.value = true
  }


}

var pageNum
const loadDataTable = async (res: any) => {
  pageNum = res.page

  return await getArrangeClassListApi({ ...res, "pageNum": pageNum });

};


function onCheckedRow(rowKeys: any) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

function confirmCreateSemester() {
  //年份 ahijinancuo 月份
  let year = new Date(selectYear.value as any)
  let term = year.getFullYear() + '-' + (year.getFullYear() + 1) + '-' + selectSemester.value
  let beginTime = createNewTermTime.value

  creatNewSemesterApi({ beginTime, term })


}

function createNewSemester() {
  showModal.value = true
}

function setWorkingSemester() {
  let id = selectOptionValue.value

  setWorkingSemesterApi(id)
}

function getLabName(id) {
  for (let lab of labList) {
    if (lab.labId == id) {
      return lab.labName
    }
  }
}

async function submitArrangeClass() {

  let labId = ArrangeClassSelectOptionValue.value
  let labName = getLabName(labId)

  //1.更新排课状态
  window['$message'].success("排课成功");
  //设置当亲排课状态为已排课--排课失败
  await updateArrangeClassApi({
    id: applicationId,
    state: 1
  })

  //2.上传排课信息
  await updataArrangeInfoClassApi({
    applicationId,
    labId,
    labName,
  })
  showArrangeClassModal.value = false
  await reloadTable()

}
</script>

<style lang="less" scoped></style>
